package logger.sd.server;

/**
 * Classe Principal Le o arquivo de configuracao e instancia o servidor, e
 * inicia o servidor de logger.
 * 
 * @author Wendell
 * 
 */
public class ServerManager {

	public static ServerConfiguration config;
	private LoggingServer server;
	private String strategy;
	private Thread runServer;

	/**
	 * Construtor
	 */
	public ServerManager() {
		config = new ServerConfiguration();
		strategy = config.getStrategy();
	}

	/**
	 * Construtor
	 */
	public ServerManager(ServerConfiguration c) {
		config = c;
		strategy = config.getStrategy();
	}

	/**
	 * Cria um LogServer
	 */
	public void createLogServer() {

		if (strategy.equals("monothread")) {
			createMonothreadLogServer();
		} else if (strategy.equals("multithread")) {
			createMultithreadLogServer(false);
		} else if (strategy.equals("threadpool")) {
			createMultithreadLogServer(true);
		} else {
			System.err.println("Erro ao iniciar o servidor.+"
					+ "\nValor de \"server.strategy\" invalido!");
			System.exit(1);
		}
	}

	/**
	 * Inicia o servidor de log padrao da API.
	 */
	public void startServer() {
		if (server != null) {

			runServer = new Thread(new Runnable() {
				public void run() {
					server.start();
				}
			});

			runServer.start();
		}
	}

	/**
	 * Finaliza o servidor
	 */
	public void stopServer() {
		server.stop();
	}

	/**
	 * Cria um MonothreadLogServer
	 */
	public void createMonothreadLogServer() {
		server = new MonothreadLoggingServer(config);
	}

	/**
	 * Cria um MultithreadLogServer
	 */
	public void createMultithreadLogServer(boolean threadpool) {
		server = new MultithreadLoggingServer(config, threadpool);
	}

	/**
	 * @return the server
	 */
	public LoggingServer getServer() {
		return server;
	}

	/**
	 * 
	 * @return the config
	 */
	public static ServerConfiguration getConfig() {
		return config;
	}

	/**
	 * Configura o servidor para iniciar com o token
	 * 
	 * @param isfirst
	 */
	public void setFirst(boolean isfirst) {
		config.setFirst(isfirst);
	}

}
